/*
Copyright 2010 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.android.gdata.project.client.activity;

import nu.zoom.android.gdata.project.client.Intents;
import nu.zoom.android.gdata.project.client.R;
import nu.zoom.android.gdata.project.client.StandardMenuHandler;
import nu.zoom.android.gdata.project.client.WKC;
import nu.zoom.android.gdata.project.client.data.PersistenceException;
import nu.zoom.android.gdata.project.client.data.ProjectnamesStorage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class GooPHIs extends ListActivity {
	private static final String LOG_TAG = WKC.LOG_TAG;
	private ArrayAdapter<String> adapter = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.projectlist);
		try {
			adapter = ProjectnamesStorage.load(this, R.layout.projectlistrow);
			setListAdapter(adapter);
		} catch (PersistenceException e) {
			Log.e(LOG_TAG, "Unable to load project names", e);
		}

		registerForContextMenu(getListView());
	}

	@Override
	protected void onStop() {
		if (adapter != null) {
			try {
				ProjectnamesStorage.save(this, adapter);
			} catch (PersistenceException e) {
				Log.e(LOG_TAG, "Unable to save project names", e);
			}
		}
		super.onStop();
	}

	@Override
	public boolean onContextItemSelected(final MenuItem item) {
		final int itemId = item.getItemId();
		final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (itemId) {
			case R.id.openproject_cmi: {
				Log.d(LOG_TAG, "Context menu item Open project");
				openProject(menuInfo.position);
				return true;
			}
			case R.id.removeproject_cmi: {
				Log.d(LOG_TAG, "Context menu item Remove project");
				removeProject(menuInfo.position);
				return true;
			}
			case R.id.editproject_cmi: {
				Log.d(LOG_TAG, "Context menu item Edit project");
				editProject(menuInfo.position);
			}
			default: {
				return super.onContextItemSelected(item);
			}
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.projectlistcontextmenu, menu);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		openProject(position);
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		StandardMenuHandler.onCreateOptionsMenu(this, menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.projectlistmenu, menu);
		return true;
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		if (resultCode != Activity.RESULT_CANCELED) {
			switch (requestCode) {
				case Intents.RequestCode.ADD_PROJECT: {
					final String projectName = data
							.getStringExtra(Intents.Extra.PROJECT_NAME);
					Log.d(LOG_TAG,
							"Add project activity returned project name ["
									+ projectName + "]");
					if ((projectName != null) && (projectName.length() > 0)) {
						adapter.add(projectName);
					}
					break;
				}
				case Intents.RequestCode.EDIT_PROJECT: {
					final String projectName = data
							.getStringExtra(Intents.Extra.PROJECT_NAME);
					final int projectIndex = data.getIntExtra(
							Intents.Extra.PROJECT_INDEX, -1);
					Log.d(LOG_TAG,
							"Edit project activity returned project name ["
									+ projectName + "] for index: "
									+ projectIndex);
					final String oldName = adapter.getItem(projectIndex);
					adapter.remove(oldName);
					adapter.insert(projectName, projectIndex);
					break;
				}
			}
		} else {
			Log.d(LOG_TAG, "Activity result code was RESULT_CANCELED");
		}
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.addProject_mi: {
				addProject();
				return true;
			}
			default:
				return StandardMenuHandler.onOptionsItemSelected(this, item);
		}
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		return StandardMenuHandler.onCreateDialog(this, id);
	}

	private void addProject() {
		Intent intent = Intents.addProject(this);
		startActivityForResult(intent, Intents.RequestCode.ADD_PROJECT);
	}

	private void editProject(final int position) {
		final String projectName = (String) getListAdapter().getItem(position);
		Intent intent = Intents.editProject(this, projectName, position);
		startActivityForResult(intent, Intents.RequestCode.EDIT_PROJECT);
	}

	private void openProject(final int position) {
		final String projectName = (String) getListAdapter().getItem(position);
		Intent intent = Intents.viewProject(this, projectName);
		startActivity(intent);
	}

	private void removeProject(final int position) {
		final String projectName = (String) getListAdapter().getItem(position);
		final String dialogMessage = String.format(
				getString(R.string.projectlist_delete_confirm_message),
				projectName);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(R.drawable.remove_project);
		builder.setTitle(R.string.projectlist_delete_confirm_title);
		builder.setMessage(dialogMessage);
		builder.setPositiveButton(
				R.string.projectlist_delete_confirm_yes_button,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Log.d(LOG_TAG, "Removing project: " + projectName);
						adapter.remove(projectName);
						final String toastText = String.format(
								getString(R.string.projectlist_delete_toast),
								projectName);
						Toast toast = Toast.makeText(GooPHIs.this, toastText,
								Toast.LENGTH_SHORT);
						toast.show();
					}
				});
		builder.setNegativeButton(
				R.string.projectlist_delete_confirm_no_button,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.d(LOG_TAG, "Cancel remove of project");
						dialog.dismiss();
					}
				});
		final AlertDialog alertDialog = builder.create();
		alertDialog.setOwnerActivity(this);
		alertDialog.show();
	}
}